package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;

import com.itheima.pojo.DishFlavor;
import com.itheima.pojo.R;
import com.itheima.service.CategoryService;

import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;



    @PostMapping
    public R addWithFlavor(@RequestBody DishDto dishDto) {
        log.info("开始新建菜品");
        dishService.addWithFlavor(dishDto);

        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("添加菜品成功!");
    }

    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        log.info("开启菜品分页查询...");

        Page<Dish> pageDish = new Page<Dish>(page, pageSize);
        Page<DishDto> pageDishDto = new Page<>();
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageDish, lqw);

        BeanUtils.copyProperties(pageDish, pageDishDto, "records");
        List<Dish> list = pageDish.getRecords();
        List<DishDto> dishDtoList = list.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        pageDishDto.setRecords(dishDtoList);
        return R.success(pageDishDto);
    }




    @GetMapping("/{id}")
    public R selectById(@PathVariable Long id) {
        log.info("更改菜品信息...");
        DishDto dishDto = dishService.selectById(id);
        return R.success(dishDto);
    }


    @PutMapping()
    public R update( @RequestBody DishDto dishDto) {
        log.info("更新菜品信息...");
        dishService.updateWithFlavor(dishDto);
        return R.success("更改菜品信息成功!");
    }



    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("售停菜品");

        List<Dish> dishList = new ArrayList<>();
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setStatus(status);
            dish.setId(id);
            dishList.add(dish);
        }
        dishService.updateBatchById(dishList);
        return R.success("售停成功!");

    }


    @DeleteMapping
    public R delete(@RequestParam List<String> ids) {
        log.info("开始删除");

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId,ids);
        dishService.remove(lqw);

        LambdaQueryWrapper<DishFlavor> lqwFlavor = new LambdaQueryWrapper<>();
        lqwFlavor.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(lqwFlavor);
        return R.success("删除成功!");

    }


    @GetMapping("/list")
    public R selectDish(Dish dish){
        log.info("根据分类查询菜品");
        List<DishDto> dishDtoList=null;
        
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();

        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList!=null){
            return R.success(dishDtoList);
        }


        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId,dish.getCategoryId()).eq(Dish::getStatus,1).orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);

        dishDtoList = list.stream().map(new Function<Dish, DishDto>() {
            @Override
            public DishDto apply(Dish dish) {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish, dishDto);
                Long categoryId = dish.getCategoryId();
                Category category = categoryService.getById(categoryId);

                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);

                Long dishId = dish.getId();

                LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
                lqw.eq(DishFlavor::getDishId, dishId);

                List<DishFlavor> dishFlavorList = dishFlavorService.list(lqw);

                dishDto.setFlavors(dishFlavorList);

                return dishDto;
            }
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

}
